package tk.pak0.audiomidifier.model.persistence;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

import org.apache.log4j.Logger;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class XmlDataHolder extends A_DataHolder {
	
	private static XmlDataHolder instance=null;
	private static Logger log = Logger.getLogger(XmlDataHolder.class);
	
	private XmlDataHolder(){
		
	}
	
	// singleton
	public static XmlDataHolder getInstance(){
		if(instance == null)
			instance = new XmlDataHolder();
		return instance;
	}

	public void makePersistent() throws IOException {
		XStream xstream = new XStream();
		xstream.alias("AudioMidifier", instance.getClass());
		FileWriter outFile = new FileWriter("./settings.xml");
        PrintWriter out = new PrintWriter(outFile);
        out.println(xstream.toXML(instance));
        out.close();
        log.info("Persistencia escrita");
	}

	@Override
	public void getPersistence() throws IOException {
		XStream xstream = new XStream(new DomDriver());
		xstream.alias("AudioMidifier", instance.getClass());
		File inFile = new File("./settings.xml");
		FileInputStream inputStream = new FileInputStream(inFile);
		xstream.fromXML(inputStream, instance);
		log.info("Persistencia cargada");
	}
	
	@Override
	public void loadDefaults() throws IOException {
		XStream xstream = new XStream(new DomDriver());
		xstream.alias("AudioMidifier", instance.getClass());
		File inFile = new File("./defaults.xml");
		FileInputStream inputStream = new FileInputStream(inFile);
		xstream.fromXML(inputStream, instance);
		log.info("Datos por defecto cargados");
	}
}
